c++ 使用boost::concept

您所在的位置:网站首页 boost库编译 windows c++ 使用boost::concept

c++ 使用boost::concept

2023-02-27 12:23| 来源: 网络整理| 查看: 265

这个概念的名称在Boost Thread源代码中不是最新的,它可能需要是BasicLockable(或者任何更具体的[标准]或扩展概念,如果适用的话)。为了避免混淆,让我们重命名宏参数:

template // Use a little bridge template externallly_locked that controls access to a BankAccount class externally_locked { // This macro is used to check that a given template parameter meets certain requirements of // has certain properties BOOST_CONCEPT_ASSERT((boost::BasicLockable)); public: externally_locked(T& obj, LockableT& lockable) : obj_(obj), lockable_(lockable) {} externally_locked(LockableT& lockable) : obj_(), lockable_(lockable) {} void set(T const& obj, LockableT& lockable) { obj_ = obj; lockable_ = lockable; } private: T obj_; LockableT& lockable_; };

看它**Live On Coliru**

#include #include #include #include #include static bool some_condition() { return rand() % 2; } // Use a little bridge template externallly_locked that controls access to a // BankAccount template class externally_locked { // This macro is used to check that a given template parameter meets // certain requirements of has certain properties BOOST_CONCEPT_ASSERT((boost::BasicLockable)); public: externally_locked(T& obj, LockableT& lockable) : obj_(obj), lockable_(lockable) {} externally_locked(LockableT& lockable) : obj_(), lockable_(lockable) {} T& get(boost::strict_lock& lock) { if (!lock.owns_lock(&lockable_)) throw boost::lock_error(); // run time check throw if not matching locks return obj_; } void set(T const& obj, LockableT& lockable) { obj_ = obj; lockable_ = lockable; } private: T obj_; LockableT& lockable_; }; class BankAccount { int balance_; public: void Deposit(int amount) { balance_ += amount; } void Withdraw(int amount) { balance_ -= amount; } }; class AccountManager : public boost::basic_lockable_adapter { public: using lockable_base_type = basic_lockable_adapter; AccountManager() : checkingAcct_(*this), savingsAcct_(*this) {} inline void Checking2Savings(int amount); inline void AMoreComplicatedChecking2Savings(int amount); private: externally_locked checkingAcct_; externally_locked savingsAcct_; }; void AccountManager::Checking2Savings(int amount) { boost::strict_lock guard(*this); checkingAcct_.get(guard).Withdraw(amount); savingsAcct_.get(guard).Deposit(amount); } int main() { AccountManager mgr; mgr.Checking2Savings(999); }

要使AccountManager::AMoreComplicatedFunction正常工作,您还需要更多的管道,如教程中所述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3